<template>
  <div class="dialog-box">
    <el-dialog v-model="dialogVisible" width="90%" draggable top="2vh" @close="handleCloseModel">
      <template #title>
        <div class="dialog-title">
          <span class="key">来水预报结果-</span>
          <span class="value">{{ state.blkcdName }}</span>
        </div>
      </template>
      <div class="result-box">
        <div class="tabs-box">
          <div class="tabs-title">
            <el-input v-model="state.name" placeholder="请输入">
              <template #append>
                <el-icon @click="handleClickIcon(state.name)">
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </div>

          <el-tree
            ref="elTreeRef"
            highlight-current
            style="max-width: 600px"
            :data="state.sectionArr"
            node-key="blkcd"
            :current-node-key="4"
            :props="{
              children: 'children',
              label: 'groupName'
            }"
            default-expand-all
            @node-click="handleClickTabs"
          >
            <template #default="{ node, data }">
              <el-tooltip
                class="item"
                effect="dark"
                placement="top"
                :content="node.label"
                :disabled="node.label.length < 6"
              >
                <div class="tree-item">
                  <span class="node">{{ node.label }}</span>
                </div>
              </el-tooltip>
            </template>
          </el-tree>
        </div>
        <div class="box-right">
          <div class="switch-box">
            <div class="box-top">
              <div class="concept-box">
                <div class="title">概化图</div>
                <div class="button-box">
                  <el-button type="text" v-if="!state.showConcept" @click="handleShowConcept"
                    >展开</el-button
                  >
                  <el-button type="text" v-else @click="handleHideConcept">收起</el-button>
                </div>
              </div>
              <div
                :class="[state.waterId == 1 ? 'echarts-img' : 'echarts-img1']"
                v-if="state.showConcept"
              >
                <mapLeftlet
                  basinCode="WDA"
                  style="height: 100%"
                  v-model:selectedSTCD="state.selectedSTCD"
                  :geojsonPath="state.mapObj"
                  :dataGetter="getReuslt"
                  @clicked="showSelected"
                  @clickedData="handleData"
                />
              </div>
            </div>
            <div class="box-bottom">
              <div class="flex-box">
                <div class="flex-box-left">
                  <span class="flex-box-title">调度方案：</span>
                  <div class="right-schems-box" v-if="state.createType != '智能预报'">
                    <el-checkbox-group v-model="state.checkValue" @change="handleCheckBox">
                      <el-checkbox
                        v-for="(item, index) in state.childSchemeList"
                        :key="index"
                        :label="item.scid"
                        >{{ item.modelName + '-' + item.disTypeName }}</el-checkbox
                      >
                    </el-checkbox-group>
                  </div>
                  <div class="right-schems-box" v-else>
                    {{ state.scNameTitle }}
                  </div>
                </div>
                <div class="flex-box-left">
                  智能水文：
                  <el-checkbox v-model="state.checkedSw" label="" size="large" />
                </div>
                <div class="flex-btn-box">
                  <div class="ul-box">
                    <div
                      v-for="(item, index) in state.showBgItem"
                      :key="index"
                      :class="['ul-item', state.flagItem == index ? 'clickBg' : '']"
                      @click="handleClickShow(index)"
                    >
                      {{ item }}
                    </div>
                  </div>
                  <div class="flex-center-box">{{ state.blkcdName }}</div>

                  <div class="flex-right-box">
                    <span class="key">推荐模型：</span>
                    <span class="value">{{ state.modelNamePush || '--' }}</span>
                  </div>
                </div>
              </div>
              <div class="tabs-name-box">
                <el-tabs
                  v-model="state.activeName"
                  class="demo-tabs"
                  @tab-change="handleClick"
                  type="border-card"
                >
                  <el-tab-pane label="过程线" name="first" lazy>
                    <div class="echarts-table-box" v-if="state.echartsVal == 'first'">
                      <div class="echarts-box" v-if="state.tableShow">
                        <SwDispatchChart
                          chart-key="detail"
                          v-if="state.waterFlag == 1"
                          height="100%"
                          :x-labels="state.sysTimes"
                          :servers="state.servers"
                          :znData="state.checkedSw ? state.znData : ''"
                        />
                        <SkDispatchChart
                          chart-key="detail"
                          v-else
                          height="100%"
                          :x-labels="state.sysTimes"
                          :servers="state.servers"
                          :znData="state.checkedSw ? state.znData : ''"
                        />
                      </div>
                      <div
                        :class="['table-box', state.tableShow ? '' : 'table-box-show']"
                        v-if="!state.showTable"
                      >
                        <el-table
                          :data="state.servers[0]?.ccResult"
                          border
                          v-if="state.waterFlag == 2"
                        >
                          <el-table-column
                            prop="tm"
                            label="时间"
                            show-overflow-tooltip
                            align="center"
                          >
                          </el-table-column>
                          <el-table-column
                            prop="fp"
                            label="降雨量"
                            show-overflow-tooltip
                            align="center"
                          >
                          </el-table-column>
                          <el-table-column
                            prop="jp"
                            label="净雨值"
                            show-overflow-tooltip
                            align="center"
                          >
                          </el-table-column>
                          <el-table-column
                            prop="name"
                            label="入库流量（实测/预报）"
                            show-overflow-tooltip
                            align="center"
                          >
                            <template #default="{ row }">
                              {{
                                `${row.rq !== '' && row.rq != undefined ? row.rq : '--'}/${
                                  row.rq !== '' && row.rq != undefined ? row.fq : '--'
                                }`
                              }}
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="address"
                            label="出库流量（实测/预报）"
                            show-overflow-tooltip
                            align="center"
                          >
                            <template #default="{ row }">
                              {{
                                `${row.otq !== '' && row.otq != undefined ? row.rotq : '--'}/${
                                  row.otq !== '' && row.otq != undefined ? row.otq : '--'
                                }`
                              }}
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="address"
                            label="水库水位（实测/预报）"
                            show-overflow-tooltip
                            align="center"
                          >
                            <template #default="{ row }">
                              {{
                                `${row.rzr !== '' ? row.rzr : '--'}/${
                                  row.zr !== '' ? row.zr : '--'
                                }`
                              }}
                            </template>
                          </el-table-column>
                        </el-table>
                        <el-table :data="state.servers[0]?.ccResult" border v-else>
                          <el-table-column
                            prop="tm"
                            label="时间"
                            show-overflow-tooltip
                            align="center"
                          >
                          </el-table-column>
                          <el-table-column
                            prop="fp"
                            label="降雨量"
                            show-overflow-tooltip
                            align="center"
                          >
                          </el-table-column>
                          <el-table-column
                            prop="jp"
                            label="净雨值"
                            show-overflow-tooltip
                            align="center"
                          >
                          </el-table-column>
                          <el-table-column
                            prop="name"
                            label="河道流量（实测/预报）"
                            show-overflow-tooltip
                            align="center"
                          >
                            <template #default="{ row }">
                              {{
                                `${row.rq !== '' ? row.rq : '--'}/${row.fq !== '' ? row.fq : '--'}`
                              }}
                            </template>
                          </el-table-column>
                          <el-table-column
                            prop="address"
                            label="河道水位（实测/预报）"
                            show-overflow-tooltip
                            align="center"
                          >
                            <template #default="{ row }">
                              {{
                                `${row.rz !== '' ? row.rz : '--'}/${row.fz !== '' ? row.fz : '--'}`
                              }}
                            </template>
                          </el-table-column>
                        </el-table>
                        <!-- <el-table :data="state.csData" style="width: 100%">
                          <el-table-column prop="prop" label="小时">
                            <template #default>
                              <el-table-column
                                v-for="(item, index) in state.nameSg"
                                :key="index"
                                align="center"
                                prop="tm1"
                                :label="item"
                              >
                              </el-table-column>
                            </template>
                          </el-table-column>
                          <el-table-column prop="prop" label="天数"> </el-table-column>
                          <el-table-column prop="prop" label="高度"> </el-table-column>
                        </el-table> -->
                      </div>
                    </div>
                    <div class="feature-box">
                      <div class="title">特征统计</div>
                      <el-table
                        :data="state.servers"
                        style="width: 100%"
                        v-if="state.waterShow == 1"
                      >
                        <!-- <el-table-column align="center" label="是否选用">
                        <template #default="{ row }">
                          <el-radio
                            v-model="state.radioItem"
                            :label="row.scid"
                            @change="handleSelectionChange(row)"
                          >
                            &nbsp;
                          </el-radio>
                        </template>
                      </el-table-column> -->
                        <el-table-column
                          prop="modelName"
                          label="预报模型"
                          align="center"
                          show-overflow-tooltip
                        />
                        <el-table-column
                          prop="disType"
                          label="调度类型"
                          align="center"
                          show-overflow-tooltip
                        />

                        <el-table-column
                          label="实测/计算入流洪峰"
                          align="center"
                          show-overflow-tooltip
                          width="150"
                        >
                          <template #default="{ row }">
                            {{
                              `${row.fcMxq !== '' && row.fcMxq != undefined ? row.rlMxq : '--'}/${
                                row.fcMxq !== '' && row.fcMxq != undefined ? row.fcMxq : '--'
                              }`
                            }}
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="address"
                          label="实测/计算入流洪现时间"
                          align="center"
                          show-overflow-tooltip
                          width="180"
                        >
                          <template #default="{ row }">
                            {{
                              `${row.fcMxt !== '' && row.fcMxt != undefined ? row.rlMxt : '--'}/${
                                row.fcMxt !== '' && row.fcMxt != undefined ? row.fcMxt : '--'
                              }`
                            }}
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="address"
                          label="实测/计算入流洪量"
                          align="center"
                          show-overflow-tooltip
                          width="150"
                        >
                          <template #default="{ row }">
                            {{
                              `${row.fcV !== '' && row.fcV != undefined ? row.rlV : '--'}/${
                                row.fcV !== '' && row.fcV != undefined ? row.fcV : '--'
                              }`
                            }}
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="address"
                          label="实测/计算最高库水位"
                          align="center"
                          show-overflow-tooltip
                          width="150"
                        >
                          <template #default="{ row }">
                            {{
                              `${row.fcMxz !== '' && row.fcMxz != undefined ? row.rlMxz : '--'}/${
                                row.fcMxz !== '' && row.fcMxz != undefined ? row.fcMxz : '--'
                              }`
                            }}
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="address"
                          label="实测/计算最大出流"
                          align="center"
                          show-overflow-tooltip
                          width="150"
                        >
                          <template #default="{ row }">
                            {{
                              `${
                                row.fcMxotq !== '' && row.fcMxotq != undefined ? row.rlMxotq : '--'
                              }/${
                                row.fcMxotq !== '' && row.fcMxotq != undefined ? row.fcMxotq : '--'
                              }`
                            }}
                          </template>
                        </el-table-column>

                        <el-table-column
                          prop="flCoef"
                          label="产流系数"
                          align="center"
                          show-overflow-tooltip
                        />
                      </el-table>
                      <el-table
                        :data="state.servers"
                        style="width: 100%"
                        v-if="state.waterShow == 2"
                      >
                        <!-- <el-table-column align="center" label="是否选用">
                        <template #default="{ row }">
                          <el-radio
                            v-model="state.radioItem"
                            :label="row.scid"
                            @change="handleSelectionChange(row)"
                          >
                            &nbsp;
                          </el-radio>
                        </template>
                      </el-table-column> -->
                        <el-table-column
                          prop="modelName"
                          label="预报模型"
                          align="center"
                          show-overflow-tooltip
                        />
                        <el-table-column
                          prop="disType"
                          label="调度类型"
                          align="center"
                          show-overflow-tooltip
                        />

                        <el-table-column
                          prop="name"
                          label="实测/计算洪峰流量"
                          align="center"
                          show-overflow-tooltip
                          width="150"
                        >
                          <template #default="{ row }">
                            {{
                              `${row.fcMxq !== '' && row.fcMxq != undefined ? row.rlMxq : '--'}/${
                                row.fcMxq !== '' && row.fcMxq != undefined ? row.fcMxq : '--'
                              }`
                            }}
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="address"
                          label="实测/计算洪现时间"
                          align="center"
                          show-overflow-tooltip
                          width="150"
                        >
                          <template #default="{ row }">
                            {{
                              `${row.fcMxt !== '' && row.fcMxt != undefined ? row.rlMxt : '--'}/${
                                row.fcMxt !== '' && row.fcMxt != undefined ? row.fcMxt : '--'
                              }`
                            }}
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="address"
                          label="实测/计算洪量"
                          align="center"
                          show-overflow-tooltip
                          width="150"
                        >
                          <template #default="{ row }">
                            {{
                              `${row.fcV !== '' && row.fcV != undefined ? row.rlV : '--'}/${
                                row.fcV !== '' && row.fcV != undefined ? row.fcV : '--'
                              }`
                            }}
                          </template>
                        </el-table-column>

                        <el-table-column
                          prop="address"
                          label="实测/计算最高水位"
                          align="center"
                          show-overflow-tooltip
                          width="150"
                        >
                          <template #default="{ row }">
                            {{
                              `${row.fcMxz !== '' && row.fcMxz != undefined ? row.rlMxz : '--'}/${
                                row.fcMxz !== '' && row.fcMxz != undefined ? row.fcMxz : '--'
                              }`
                            }}
                          </template>
                        </el-table-column>

                        <el-table-column
                          prop="flCoef"
                          label="产流系数"
                          align="center"
                          show-overflow-tooltip
                        />
                      </el-table>
                    </div>
                  </el-tab-pane>
                  <el-tab-pane label="水库信息" name="second" v-if="state.sttp == 'RR'" lazy>
                    <waterInfo
                      v-if="state.echartsVal == 'second'"
                      :blkcdWater="state.blkcdId"
                      :rscd="state.rscd"
                      :scidObj="state.sdObj"
                    />
                  </el-tab-pane>
                  <el-tab-pane label="河道站点信息" name="second" v-if="state.sttp !== 'RR'" lazy>
                    <waterSiteInfo
                      :blkcdWater="state.blkcdId"
                      :rscd="state.rscd"
                      :scidObj="state.sdObj"
                      :stcd="state.selectedSTCD"
                    />
                  </el-tab-pane>
                </el-tabs>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, nextTick, watch, onMounted } from 'vue'
import waterInfo from './cpns/waterInfo/index.vue'
import waterSiteInfo from './cpns/waterSiteInfo/index.vue'
import testData from '@/assets/data/map_data/yshInfo/test.json'
import Map from '@/components/app-map/map_part.vue'
//水文
import SwDispatchChart from '@/components/app-echart/sw-dispatch-chart.vue'
//水库
import SkDispatchChart from '@/components/app-echart/sk-dispatch-chart.vue'
//概画图
import mapLeftlet from '@/components/app-map/map_leaflet/hairtailSchematicDiagram.vue'
import {
  useDispatchManage1,
  useDispatchManage,
  useDispatchManageBlkcd
} from '@/store/modules/dispatch-manage.js'
import { storeToRefs } from 'pinia'
import { assignUniqueIds, assignByParams } from '@/utils/index'
import {
  getGradeSections,
  getManualSchemesresult,
  getDispatchSchemeDetail,
  // 推送
  postSaveResultPush,
  getAiForecastResult
} from '@/services/modules/dispatch-manage'
import { addTileLayer } from '@/utils/mapUtils'
import emitter from '@/utils/bus'

// 地图初始化参数
const mapOptions = { crs: 'EPSG:4490', basemaps: [] }
const state = reactive({
  createType: '',
  scNameTitle: '',
  // csData: [
  //   { tm: '12:00', date: '2023', height: 280, name: '菠萝', bj: '' },
  //   { tm: '12:00', date: '2023', height: 200, name: '菠萝', bj: '' },
  //   { tm: '12:00', date: '2023', height: 230, name: '菠萝', bj: '' },
  //   { tm: '12:00', date: '2023', height: 220, name: '菠萝', bj: '' },
  //   { tm1: '13:00', date: '2023', height: 100, name: '橘子', bj: '' },
  //   { tm1: '13:00', date: '2023', height: 120, name: '橘子', bj: '' },
  //   { tm1: '13:00', date: '2023', height: 180, name: '橘子', bj: '' },
  //   { tm1: '13:00', date: '2023', height: 180, name: '橘子', bj: '' }
  // ],
  // nameSg: ['菠萝', '橘子'],
  checkedSw: false,
  selectedSTCD: '',
  rscd: '',
  sttp: '',
  showConcept: false,
  // 推荐模型名称
  modelNamePush: '',
  radioItem: '',
  waterShow: 1,
  checkedScheme: [],
  modelInfo: [],
  checkModelType: [],
  checkModels: [],
  models: [],
  modelType: [],
  flagItem: 0,
  tableShow: true,
  scName: '',
  blkcdName: '',
  scid: '',
  activeName: 'first',
  showTable: true,
  collapseActive: '1',
  servers: [],
  waterFlag: 1,
  sectionArr: [],
  blkcdId: '',
  tabNewData: [],
  evaResult: {},
  tableData: [
    {
      address: 'fsdf',
      name: '章三',
      date: '新安江'
    },
    {
      address: 'fsdf',
      name: '章三',
      date: '新安江'
    },
    {
      address: 'fsdf',
      name: '章三',
      date: '新安江'
    },
    {
      address: 'fsdf',
      name: '章三',
      date: '新安江'
    }
  ],
  //时间
  sysTimes: [],
  //降雨量
  rainArr: [],
  //实测流量
  rqArr: [],
  //模拟流量
  fqArr: [],
  //实测水位
  rzArr: [],
  //模拟水位
  fzArr: [],
  showBgItem: ['图', '混', '表'],
  // 子方案列表
  childSchemeList: [],
  // 多选框选中的值
  checkValue: [],
  // 存储调度方案的值，弹框关闭或者选择其它水库时将其清空
  scidStoreArr: [],
  // 暂时存储计算结果的数组
  serversStore: []
})
// 多选框选择调度方案回调
async function handleCheckBox() {
  // 暂存没有选择过的scid
  let zcIdArr = []
  nextTick(() => {
    emitter.emit('clearEcharts')
    emitter.emit('initEcharts')
  })
  if (state.checkValue.length > 0) {
    state.checkValue.forEach(async (e) => {
      // 如果结果数组中没有选中的这个方案的id

      if (!state.scidStoreArr.includes(e)) {
        zcIdArr.push(e)
      } else {
        // 如存在 则将结果数组中的对应checkValue的scid的对象全部拿出
        state.servers = []

        state.serversStore.forEach((a) => {
          if (state.checkValue.includes(a?.scid)) {
            state.servers.push(a)
          }
        })

        console.log(state.servers, '全部')
      }
    })
    // 调用接口获取结果
    await acceptComputedResult(zcIdArr)
    // 获取智能结果
    acceptAiForecastResult()
    if (zcIdArr.length) {
      state.servers = []
      state.serversStore.forEach((a) => {
        if (state.checkValue.includes(a?.scid)) {
          state.servers.push(JSON.parse(JSON.stringify(a)))
        }
      })
      // state.servers = JSON.parse(JSON.stringify(state.serversStore))
    }
    // state.checkValue.forEach(async (e) => {
    //   // 如果结果数组中没有选中的这个方案的id
    //   if (!state.scidStoreArr.includes(e)) {
    //     // 则调用接口获取
    //     await acceptComputedResult(e)
    //     state.servers = JSON.parse(JSON.stringify(state.serversStore))
    //   } else {
    //     // 如存在 则将结果数组中的对应checkValue的scid的对象全部拿出
    //     state.servers = []

    //     state.serversStore.forEach((a) => {
    //       if (state.checkValue.includes(a?.scid)) {
    //         state.servers.push(a)
    //       }
    //     })
    //   }
    // })
  } else {
    state.servers = []
    state.sysTimes = []
    state.checkedSw = false
  }
  handleIspush(state.servers)
}
//展开
function handleShowConcept() {
  state.showConcept = true
}
//收起
function handleHideConcept() {
  state.showConcept = false
}

const dialogVisible = ref(false)

// //订阅
// const subscribe = useDispatchManageBlkcd().$subscribe(
//   (mutation, state) => {
//     if (state.blkcd) {
//       if (
//         useDispatchManage1().leftSelectList == '实测预报降雨' ||
//         useDispatchManage1().leftSelectList == '典型场次'
//       ) {
//         handleOpenModal(
//           useDispatchManage1().scidDialog,
//           useDispatchManage1().watershedId,
//           state.blkcd
//         )
//       }
//     }
//   },
//   { detached: false }
// )
watch(
  () => storeToRefs(useDispatchManageBlkcd()).showDialogResult.value,
  () => {
    if (storeToRefs(useDispatchManageBlkcd()).showDialogResult.value == true) {
      dialogVisible.value = true
      handleOpenModal(
        useDispatchManageBlkcd().scid,
        useDispatchManageBlkcd().waterFlag,
        useDispatchManageBlkcd().blkcd,
        useDispatchManageBlkcd().scNameObj
      )
    }
  },
  {
    deep: true
  }
)
const elTreeRef = ref(null)
// 选中map中的某一项 对应左侧选中效果
function showSelectedSubscribe(blkcd) {
  elTreeRef.value?.setCurrentKey(blkcd)
  handleClickTabs(assignByParams(state.sectionArr, 'blkcd', blkcd))
}

// 获取智能结果
function acceptAiForecastResult() {
  // debugger
  state.sysTimes = []
  getAiForecastResult({ scid: state.scid, blkcd: state.blkcdId }).then((res) => {
    if (res.code == 200) {
      state.znData = res.data
      state.znData.forEach((item) => {
        state.sysTimes.push(item.tm)
      })
      // state.servers.push({ ccResult: res.data, warnInfo: {} })
      console.log(state.servers, '最终数据')
    }
  })
}
// 打开弹框
async function handleOpenModal(scid, waterId, blkcd, scNameObj) {
  state.scid = scid
  dialogVisible.value = true
  state.scNameTitle = scNameObj.scNameTitle
  state.createType = scNameObj.type
  handleClick('first')
  handleHideConcept()
  // 流域id
  if (scid) {
    state.waterId = waterId
    if (waterId == 1) {
      state.mapObj = {
        WDA: {
          gaihuatuPath: './data/gaihuatuDWHHairtail.geojson'
        }
      }
    } else if (waterId == 2) {
      state.mapObj = {
        WDA: {
          gaihuatuPath: 'data/gaihuatuYSH.geojson'
        }
      }
    }
    // 获取子方案列表
    await acceptChildList(scid)
    // 获取断面列表
    await handleClickIcon('')
    // 回显水库
    showSelectedSubscribe(blkcd)
  } else {
    state.servers = []
    state.sdObj = {}
    state.childSchemeList = []
    state.sectionArr = []
  }
}
// 获取子方案列表
function acceptChildList(scid) {
  return new Promise((resolve, reject) => {
    getDispatchSchemeDetail({ scid, scBelong: 0 }).then((res) => {
      if (res.code === 200) {
        state.sdObj = res.data
        // 获取子方案
        state.childSchemeList = res.data?.models?.info
        // 默认选中第一个子方案
        state.checkValue = [state.childSchemeList[0]?.scid]
        resolve(res.data)
      }
    })
  })
}

function handleCloseModel() {
  storeToRefs(useDispatchManageBlkcd()).showDialogResult.value = false
  state.servers = []
  state.serversStore = []
  state.scidStoreArr = []
  state.checkValue = []
  // useDispatchManage1().$reset()
  dialogVisible.value = false
}
//展开
function handleClickShow(val) {
  state.flagItem = val
  // state.showTable = !state.showTable;
  if (val == 0) {
    // 图

    state.tableShow = false
    setTimeout(() => {
      state.showTable = true
      state.tableShow = true
    }, 100)
  } else if (val == 1) {
    state.tableShow = false
    // 混
    setTimeout(() => {
      state.showTable = false
      state.tableShow = true
    }, 100)
  } else {
    //表
    state.showTable = false
    // 将图关闭
    state.tableShow = false
  }

  // emitter.emit('clearEcharts')
  emitter.emit('initEcharts')
}
function handleClick(val) {
  emitter.emit('initEcharts')
  setTimeout(() => {
    state.echartsVal = val
  }, 100)
}
//点击推送
function handleSelectionChange(row) {
  // 推送的模型名称

  postSaveResultPush({
    scid: row.scid,
    blkcd: row.blkcd,
    model: row.model,
    pscid: state.scid
  }).then((res) => {
    if (res.code == 200) {
      state.modelNamePush = row.modelName
      state.radioItem = row.scid

      ElMessage.success('推送成功')
    }
  })
}
// 判断是否已经推送
function handleIspush(servesData) {
  let newArr = servesData.filter((item) => {
    return item.isPush == 1
  })

  state.radioItem = newArr[0]?.scid
  state.modelNamePush = newArr[0]?.modelName
}
//收起
function handleClickHide() {
  state.showTable = !state.showTable
  nextTick(() => {
    // emitter.emit('clearEcharts')
    emitter.emit('initEcharts')
  })
}
const handleMapLoad = ({ map }) => {
  const layerUrlS = mapUrl
  addTileLayer(map, layerUrlS, 0, 74, '山东底图')
}
function updateLeafProperty(data) {
  // 递归函数，只修改最后一层的属性名
  const isLeaf = (item) => !Array.isArray(item.children)
  const update = (item) => {
    if (isLeaf(item)) {
      if (Object.prototype.hasOwnProperty.call(item, oldPropertyName)) {
        item[newPropertyName] = item[oldPropertyName]
        delete item[oldPropertyName]
      }
    } else {
      item.children = item.children.map(update)
    }
    return item
  }
  const oldPropertyName = 'blknm'
  const newPropertyName = 'groupName'
  state.sectionArr = data.map(update)
  assignUniqueIds(state.sectionArr)
  console.log(state.sectionArr, '888888')
  // handleClickTabs(state.sectionArr[0].children[0].children[0].children[0], 0)
}
// 搜索断面
function handleClickIcon(name) {
  return new Promise((resolve, reject) => {
    getGradeSections({ scid: state.scid, blknm: name || '' }).then((res) => {
      if (res.code === 200) {
        state.sectionArr = res.data
        updateLeafProperty(state.sectionArr)
        // if (state.sectionArr.length) {
        //   handleClickTabs(state.sectionArr.filter((v) => v.sttp == 'RR')[0], 0)
        // }
        resolve(res.data)
      }
    })
  })
}
// 选中概化图中的某一项 对应左侧选中效果
function showSelected(elem) {
  handleClickTabs(assignByParams(state.sectionArr, 'stcd', elem.properties.STCD))
  elTreeRef.value?.setCurrentKey(
    assignByParams(state.sectionArr, 'stcd', elem.properties.STCD).blkcd
  )
}

// 点击水库
async function handleClickTabs(item) {
  if (!item?.blkcd) {
    return false
  }
  state.sttp = item.sttp
  state.selectedSTCD = item.stcd
  state.rscd = item?.rscd

  if (item) {
    state.blkcdName = item?.groupName
    state.blkcdId = item?.blkcd ? item?.blkcd : ''
    state.checkedSw = false
    // currentIndex.value = index
    if (item.sttp == 'RR') {
      // 点击为水库
      state.waterShow = 1
      state.waterFlag = 2
    } else {
      // 点击的为水文站
      state.waterShow = 2
      state.waterFlag = 1
    }
  }

  // 点击水库，将存储的方案结果和id，图表传的值 都清空，并默认选中第一个方案
  state.serversStore = []
  state.scidStoreArr = []
  state.servers = []
  // state.checkValue = [state.childSchemeList[0]?.scid]
  if (state.createType == '智能预报') {
    // 获取智能结果
    acceptAiForecastResult()
  } else {
    handleCheckBox()
  }
}
// 获取计算结果
async function acceptComputedResult(scidArr) {
  if (scidArr.length > 0) {
    return new Promise((resolve, reject) => {
      getManualSchemesresult({
        scid: scidArr.join(),
        blkcd: state.blkcdId
      }).then((res) => {
        if (res.code === 200) {
          if (res.data.length) {
            let arr = []
            arr = res.data.map((item) => {
              return {
                ...item,
                result: [{ ccResult: item.ccResult, warnInfo: item.warnInfo }]
                // result: [{ ccResult: testData, warnInfo: item.warnInfo }]
              }
            })
            // if (state.checkValue.length > 1) {
            state.serversStore.push(...arr)
            // } else {
            //   state.serversStore = arr
            // }
            // state.serversStore.push(arr[0])

            state.serversStore.forEach((e) => {
              state.scidStoreArr.push(e.scid)
            })
            // 数组去重 结果去重
            state.serversStore = Array.from(
              new Set(state.serversStore.map(JSON.stringify)),
              JSON.parse
            )
            // scid去重
            state.scidStoreArr = Array.from(new Set(state.scidStoreArr))
            resolve(res.data)
          }
        }
      })
    })
  }
}
defineExpose({ handleOpenModal })
</script>

<style lang="less" scoped>
.dialog-box {
  :deep(.el-dialog__body) {
    padding-top: 10px !important;
  }
}

.dialog-title {
  padding-bottom: 5px;
  height: 25px;
  border-bottom: 2px solid #eee;
  // font-size: 14px;
  font-size: var(--header-fontsize);
  .key {
    color: #4fc0f1;
  }
  .value {
    color: #424242;
  }
}
.result-box {
  width: 100%;
  height: 90vh;
  display: flex;
  .tabs-box {
    width: 200px;
    height: calc(100% - 8px);
    margin-right: 10px;
    border: 1px solid #c8c2c29d;
    border-radius: 3px;
    overflow: hidden;
    .tabs-title {
      height: 30px;
      background: #f2f2f2;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      span {
        font-weight: 600;
      }
    }
    :deep(.el-tree) {
      height: calc(100% - 40px);
      overflow-y: auto;
      margin-top: 5px;
      .el-tree-node {
        &.is-focusable.is-current {
          > div:nth-of-type(1) {
            color: #409eff;
            font-weight: 600;
            font-size: 15px;
          }
        }
        .el-tree-node__content {
          margin-top: 5px;
        }
      }
      .position-btn {
        margin-right: 20px;
      }
      .position-btn:hover {
        color: #0154db;
      }
      .tree-item {
        &.active {
          span {
            color: #0154db;
          }
        }
        .node {
          width: 100px;
          display: inline-block;
          overflow: hidden; /* 确保超出容器的文本被裁剪 */
          white-space: nowrap; /* 确保文本在一行内显示 */
          text-overflow: ellipsis; /* 超出部分显示为省略号 */
          // font-size: var(--content-fontsize);
        }
      }
    }

    :deep(.el-collapse) {
      height: calc(100% - 30px);
      .mg10 {
        margin-left: 10px;
        width: 100%;
        text-align: center;
      }
      .el-collapse-item.is-active {
        height: calc(100% - 82px);
        .el-collapse-item__wrap {
          height: 100%;
          .el-collapse-item__content {
            height: calc(100% - 80px);
            overflow-y: auto;
          }
        }
      }
    }
    .tabs-list {
      // height: calc(100% - 30px);
      // background: #d7d4d427;
      // overflow-y: auto;
      .list-item {
        width: 100%;
        height: 30px;
        text-align: center;
        cursor: pointer;
        &.active {
          span {
            color: #0154db;
          }
        }
        span {
          width: 100%;
          color: black;
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
      .list-item:hover {
        width: 100%;
        height: 30px;
        cursor: pointer;
        span {
          color: #0154db;
        }
      }
    }
  }
  .box-right {
    flex: 1;
    width: calc(100% - 155px);
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;

    .comput-times {
      width: 100%;
      height: 70px;
      .times-title {
        height: 30px;
        span {
          font-weight: 600;
        }
      }
      .times-list {
        display: flex;
        width: 100%;
        height: 40px;
        overflow-x: auto;
        white-space: nowrap;
        .times-item {
          width: 200px;
          height: 30px;
          border: 1px solid gray;
          border-radius: 8px;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 10px;
          padding: 0 15px;
          cursor: pointer;
          &.active {
            span {
              color: #0154db;
            }
          }
          &:hover {
            color: #0154db;
          }
          span {
            color: gray;
          }
        }
      }
    }
    .switch-box {
      width: 100%;
      height: 100%;
      .box-top {
        .concept-box {
          display: flex;
          justify-content: space-between;
          .title {
            font-size: 18px;
          }
          .button-box {
          }
        }
        .echarts-img {
          width: 100%;
          height: 300px;
          :deep(.map-container) {
            height: 100% !important;
          }
          img {
            width: 100%;
            height: 100%;
          }
        }
        .echarts-img1 {
          width: 100%;
          height: 400px;
          :deep(.map-container) {
            height: 100% !important;
          }
          img {
            width: 100%;
            height: 100%;
          }
        }
      }

      .box-bottom {
        height: 800px;
        .right-btn-plus {
          width: 100%;
          height: 50px;
          display: flex;
          // justify-content: flex-end;
          .title {
            line-height: 50px;
            color: #409eff;
            width: 100%;
            text-align: center;
            // margin-right: 40%;
          }
          .btn-plus {
            font-size: 25px;
            font-weight: bold;
          }
        }
        .flex-box {
          margin-bottom: 10px;
          .flex-box-left {
            width: 100%;
            height: 50px;
            display: flex;
            align-items: center;
            .flex-box-title {
              width: 80px;
              font-size: 14px;
              font-weight: 600;
              color: #797979;
            }
            .right-schems-box {
              width: calc(100% - 150px);
              overflow-x: auto;
              white-space: nowrap;
              // margin-right: 30px;
            }
          }
        }
        .flex-btn-box {
          display: flex;
          margin-top: 10px;
          justify-content: space-between;

          // justify-content: flex-end;
          // justify-content: flex-end;
          .flex-right-box {
            line-height: 100%;
            margin-right: 20px;
            text-align: center;
            line-height: 20px;
            .key {
              color: #797979;
            }
            .value {
              color: #409eff;
            }
          }
          .flex-center-box {
            color: #409eff;
          }
          .ul-box {
            display: flex;
            justify-content: space-around;
            line-height: 100%;
            margin-right: 50px;
            text-align: center;
            // margin-bottom: 20px;
            width: 100px;
            height: 100%;
            border-radius: 20px;
            background-color: rgba(1, 84, 219, 0.3);

            .ul-item {
              width: 30px;
              height: 20px;
              border-radius: 20px;
              // background-color: #0154db;
              color: #ffffff;
              cursor: pointer;
              line-height: 20px;
              &:hover {
                background-color: #0154db;
                color: wheat;
              }
            }
            .clickBg {
              background-color: #0154db;
            }
          }
        }
        .tabs-name-box {
          width: 100%;
          height: auto;
          :deep(.el-tabs) {
            z-index: 11;
            height: 100%;
            .el-tabs__content {
              height: calc(100% - 80px);
              .echarts-table-box {
                display: flex;
                width: 100%;
                height: 600px;
                position: relative;
                overflow-y: auto;
                overflow-x: hidden;

                .echarts-box {
                  flex: 1;
                  width: auto;
                  min-width: 49%;
                  // max-width: 100%;
                  height: 100%;
                  // height: 500px;

                  // height: calc(100%);
                  // padding: 5px;
                  position: relative;
                  .show-btn {
                    cursor: pointer;
                    position: absolute;
                    right: 0px;
                    top: 0px;
                  }
                }
                .table-box {
                  width: 50%;
                  max-width: 100%;
                  margin-left: 1%;
                  position: relative;
                  .el-table {
                    height: 100%;
                  }
                  .hide-btn {
                    cursor: pointer;
                    position: absolute;
                    height: 20px;
                    top: 10px;
                    right: 0;
                    z-index: 10;
                  }
                }
                .table-box-show {
                  width: 100% !important;
                }
              }
              .feature-box {
                width: 100%;
                height: calc(100% - 360px);
                overflow-x: auto;
                .title {
                  color: #409eff;
                  margin: 5px 0 5px 20px;
                }
                :deep(.el-table) {
                  height: calc(100% - 20px);
                }
              }
              .el-tab-pane {
                height: 100%;
                overflow-y: auto;
                .el-table {
                  height: 150px;
                  overflow-y: auto;
                }
              }
            }
          }
        }
      }

      .btn-box {
        margin-right: 100px;
        display: flex;
        .btn-box-color {
          color: #797979;
          display: flex;
          align-items: center;
          margin-right: 20px;
        }
        .el-checkbox-group {
          margin-right: 10px;
        }
        span {
          margin-right: 10px;
          line-height: 30px;
        }
        // text-align: right;
        // margin-right: 15px;
        // height: 30px;
      }
    }
  }
}
</style>
